from  rest_framework.serializers import ModelSerializer,ValidationError
from rest_framework import serializers
from sys_manager.models import  UserModel


import re

from sys_manager.serializer_kit.dept_serializer import DeptSerializer
from sys_manager.serializer_kit.roles_serializer import RolesSerializer


class UserAddSerializer(ModelSerializer):

    class Meta:
        model=UserModel
        fields=['id','username','password','phone','real_name']
        extra_kwargs ={
           'username': {
                'max_length':12,
               'min_length':2
            },

            'password':{
                'max_length': 8,
                'min_length':3,
                'write_only':True

            },


        }

    #校验手机号
    def validate_phone(self,phone):
        if not re.match(r'^1[3579]\d{9}$',phone):
            return ValidationError('请输入正确的手机号')

        return  phone

    def create(self, validated_data):
        #将加密的密码以及其他字段数据插入到数据库中
        user=UserModel.objects.create_user(**validated_data)

        return user


class UpdateOrDestroySerializer(ModelSerializer):
    class Meta:
        model=UserModel
        fields=['id','phone','real_name','roles','dept']

class RetrieveSerilizer(ModelSerializer):
    class Meta:
        model=UserModel
        roles=RolesSerializer(many=True,read_only=True)
        dept=DeptSerializer(many=False,read_only=True)

        fields=['id','username','roles','dept']


class ResetPasswordSerilizer(ModelSerializer):
    '''
    包含三个参数 包含原始密码 新密码 新密码确认
    '''
    new_password=serializers.CharField(required=True,write_only=True)
    conf_new_password=serializers.CharField(required=True,write_only=True)

    class Meta:
        model=UserModel

        fields=['id','password','new_password','conf_new_password']
        extra_kwargs={

            'password':{'write_only':True},
            'new_password': {'write_only': True},
            'conf_new_password': {'write_only': True}
        }

    def validate(self, attrs):

        '''表单参数验证'''
        password=attrs.get('password')
        new_password = attrs.get('new_password')
        conf_new_password = attrs.get('conf_new_password')

        if not password:
            raise ValidationError('字段password为必传项')
        if not new_password:
            raise ValidationError('字段new_password为必传项')
        if not conf_new_password:
            raise ValidationError('字段conf_new_password为必传项')
        if new_password!=conf_new_password:
            raise  ValidationError('两次密码不一致')


        return attrs

    def save(self, **kwargs):
        if not self.instance.check_password(self.validated_data.get('password')):
            raise ValidationError('密码不一致')

        self.instance.set_password(self.validated_data.get('new_password'))

        self.instance.save()
        return self.instance